# 高级分析和报表数据模型
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import json


class ReportTemplate(models.Model):
    """报表模板"""
    
    REPORT_TYPE_CHOICES = [
        ('chart', '图表报表'),
        ('table', '表格报表'),
        ('dashboard', '仪表板'),
        ('pivot', '透视表'),
        ('kpi', 'KPI指标'),
    ]
    
    CHART_TYPE_CHOICES = [
        ('line', '折线图'),
        ('bar', '柱状图'),
        ('pie', '饼图'),
        ('area', '面积图'),
        ('scatter', '散点图'),
        ('gauge', '仪表盘'),
        ('radar', '雷达图'),
        ('heatmap', '热力图'),
    ]
    
    name = models.CharField('报表名称', max_length=100)
    description = models.TextField('报表描述', blank=True)
    report_type = models.CharField('报表类型', max_length=20, choices=REPORT_TYPE_CHOICES)
    chart_type = models.CharField('图表类型', max_length=20, choices=CHART_TYPE_CHOICES, blank=True)
    
    # 数据源配置
    data_source = models.CharField('数据源', max_length=50)  # 模型名称
    query_config = models.JSONField('查询配置', default=dict)
    
    # 报表配置
    report_config = models.JSONField('报表配置', default=dict)
    layout_config = models.JSONField('布局配置', default=dict)
    
    # 权限和共享
    is_public = models.BooleanField('公开报表', default=False)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建人')
    shared_users = models.ManyToManyField(User, related_name='shared_reports', blank=True, verbose_name='共享用户')
    
    # 调度配置
    is_scheduled = models.BooleanField('定时生成', default=False)
    schedule_config = models.JSONField('调度配置', default=dict)
    
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    is_active = models.BooleanField('是否启用', default=True)
    
    class Meta:
        verbose_name = '报表模板'
        verbose_name_plural = '报表模板'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name
    
    def get_report_type_display_icon(self):
        """获取报表类型图标"""
        icons = {
            'chart': 'fas fa-chart-line',
            'table': 'fas fa-table',
            'dashboard': 'fas fa-tachometer-alt',
            'pivot': 'fas fa-th',
            'kpi': 'fas fa-bullseye',
        }
        return icons.get(self.report_type, 'fas fa-chart-bar')


class Dashboard(models.Model):
    """仪表板"""
    
    name = models.CharField('仪表板名称', max_length=100)
    description = models.TextField('描述', blank=True)
    
    # 布局配置
    layout_config = models.JSONField('布局配置', default=dict)
    widgets = models.JSONField('组件配置', default=list)
    
    # 权限设置
    is_public = models.BooleanField('公开仪表板', default=False)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建人')
    shared_users = models.ManyToManyField(User, related_name='shared_dashboards', blank=True)
    
    # 刷新设置
    auto_refresh = models.BooleanField('自动刷新', default=False)
    refresh_interval = models.IntegerField('刷新间隔(秒)', default=300)
    
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    is_active = models.BooleanField('是否启用', default=True)
    
    class Meta:
        verbose_name = '仪表板'
        verbose_name_plural = '仪表板'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name


class ReportExecution(models.Model):
    """报表执行记录"""
    
    STATUS_CHOICES = [
        ('pending', '等待中'),
        ('running', '执行中'),
        ('completed', '已完成'),
        ('failed', '执行失败'),
    ]
    
    template = models.ForeignKey(ReportTemplate, on_delete=models.CASCADE, verbose_name='报表模板')
    executed_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='执行人')
    
    status = models.CharField('执行状态', max_length=20, choices=STATUS_CHOICES, default='pending')
    
    # 执行参数
    parameters = models.JSONField('执行参数', default=dict)
    
    # 执行结果
    result_data = models.JSONField('结果数据', default=dict)
    result_file = models.FileField('结果文件', upload_to='reports/', blank=True)
    
    # 执行时间
    started_at = models.DateTimeField('开始时间', null=True, blank=True)
    completed_at = models.DateTimeField('完成时间', null=True, blank=True)
    
    # 错误信息
    error_message = models.TextField('错误信息', blank=True)
    
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    
    class Meta:
        verbose_name = '报表执行记录'
        verbose_name_plural = '报表执行记录'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.template.name} - {self.created_at.strftime('%Y-%m-%d %H:%M')}"
    
    @property
    def execution_time(self):
        """执行时长"""
        if self.started_at and self.completed_at:
            return (self.completed_at - self.started_at).total_seconds()
        return None


class DataAnalysisTask(models.Model):
    """数据分析任务"""
    
    TASK_TYPE_CHOICES = [
        ('trend', '趋势分析'),
        ('correlation', '相关性分析'),
        ('forecast', '预测分析'),
        ('clustering', '聚类分析'),
        ('anomaly', '异常检测'),
        ('comparison', '对比分析'),
    ]
    
    STATUS_CHOICES = [
        ('pending', '等待中'),
        ('running', '分析中'),
        ('completed', '已完成'),
        ('failed', '分析失败'),
    ]
    
    name = models.CharField('任务名称', max_length=100)
    task_type = models.CharField('分析类型', max_length=20, choices=TASK_TYPE_CHOICES)
    
    # 数据源配置
    data_source = models.CharField('数据源', max_length=50)
    query_config = models.JSONField('查询配置', default=dict)
    
    # 分析配置
    analysis_config = models.JSONField('分析配置', default=dict)
    
    # 执行状态
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='pending')
    progress = models.IntegerField('进度', default=0)
    
    # 结果
    result_data = models.JSONField('分析结果', default=dict)
    insights = models.JSONField('分析洞察', default=list)
    
    # 执行信息
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建人')
    started_at = models.DateTimeField('开始时间', null=True, blank=True)
    completed_at = models.DateTimeField('完成时间', null=True, blank=True)
    error_message = models.TextField('错误信息', blank=True)
    
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    
    class Meta:
        verbose_name = '数据分析任务'
        verbose_name_plural = '数据分析任务'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name


class KPIMetric(models.Model):
    """KPI指标"""
    
    METRIC_TYPE_CHOICES = [
        ('count', '计数'),
        ('sum', '求和'),
        ('avg', '平均值'),
        ('max', '最大值'),
        ('min', '最小值'),
        ('ratio', '比率'),
        ('growth', '增长率'),
    ]
    
    TREND_CHOICES = [
        ('up', '上升'),
        ('down', '下降'),
        ('stable', '稳定'),
    ]
    
    name = models.CharField('指标名称', max_length=100)
    description = models.TextField('指标描述', blank=True)
    
    # 计算配置
    metric_type = models.CharField('指标类型', max_length=20, choices=METRIC_TYPE_CHOICES)
    data_source = models.CharField('数据源', max_length=50)
    calculation_config = models.JSONField('计算配置', default=dict)
    
    # 目标值
    target_value = models.FloatField('目标值', null=True, blank=True)
    warning_threshold = models.FloatField('警告阈值', null=True, blank=True)
    critical_threshold = models.FloatField('严重阈值', null=True, blank=True)
    
    # 当前值
    current_value = models.FloatField('当前值', null=True, blank=True)
    previous_value = models.FloatField('上期值', null=True, blank=True)
    trend = models.CharField('趋势', max_length=10, choices=TREND_CHOICES, blank=True)
    
    # 更新配置
    auto_update = models.BooleanField('自动更新', default=True)
    update_frequency = models.IntegerField('更新频率(分钟)', default=60)
    last_updated = models.DateTimeField('最后更新', null=True, blank=True)
    
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建人')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    is_active = models.BooleanField('是否启用', default=True)
    
    class Meta:
        verbose_name = 'KPI指标'
        verbose_name_plural = 'KPI指标'
        ordering = ['name']
    
    def __str__(self):
        return self.name
    
    @property
    def status(self):
        """获取指标状态"""
        if not self.current_value:
            return 'unknown'
        
        if self.critical_threshold:
            if self.current_value <= self.critical_threshold:
                return 'critical'
        
        if self.warning_threshold:
            if self.current_value <= self.warning_threshold:
                return 'warning'
        
        if self.target_value:
            if self.current_value >= self.target_value:
                return 'good'
            else:
                return 'below_target'
        
        return 'normal'
    
    @property
    def change_rate(self):
        """变化率"""
        if self.current_value and self.previous_value and self.previous_value != 0:
            return ((self.current_value - self.previous_value) / self.previous_value) * 100
        return 0


class ReportSubscription(models.Model):
    """报表订阅"""
    
    FREQUENCY_CHOICES = [
        ('daily', '每日'),
        ('weekly', '每周'),
        ('monthly', '每月'),
        ('quarterly', '每季度'),
    ]
    
    FORMAT_CHOICES = [
        ('pdf', 'PDF'),
        ('excel', 'Excel'),
        ('email', '邮件'),
    ]
    
    template = models.ForeignKey(ReportTemplate, on_delete=models.CASCADE, verbose_name='报表模板')
    subscriber = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='订阅人')
    
    frequency = models.CharField('频率', max_length=20, choices=FREQUENCY_CHOICES)
    format = models.CharField('格式', max_length=20, choices=FORMAT_CHOICES)
    
    # 发送配置
    email_recipients = models.JSONField('邮件接收人', default=list)
    send_time = models.TimeField('发送时间', default='08:00')
    
    # 参数配置
    parameters = models.JSONField('报表参数', default=dict)
    
    # 状态
    is_active = models.BooleanField('是否启用', default=True)
    last_sent = models.DateTimeField('最后发送', null=True, blank=True)
    next_send = models.DateTimeField('下次发送', null=True, blank=True)
    
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    
    class Meta:
        verbose_name = '报表订阅'
        verbose_name_plural = '报表订阅'
        unique_together = ['template', 'subscriber']
    
    def __str__(self):
        return f"{self.subscriber.username} - {self.template.name}"